import {
    app,
    BrowserWindow,
    screen,
    dialog, ipcMain
} from 'electron'
let path = require('path');
import creatEmptyResourceWindow from './resource'
import globalConst from '../renderer/content/global/const/index'
import {
    SqlLib
} from '../../static/lib/sqlite/SqlLib';
/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
    global.__static = path.join(__dirname, '/static').replace(/\\/g, '\\\\')
}



let mainWindow
let dbPath = ''
let outPath = ''
const winURL = process.env.NODE_ENV === 'development' ?
    `http://localhost:9080/content` :
    `file://${__dirname}/content/index.html`

function createWindow () {
    /**
     * Initial window options
     */
    let {
        width,
        height
    } = screen.getPrimaryDisplay().workAreaSize;

    if (width > 1439 && height > 899) {
        width = 1440;
        height = 900;
    } else {
        width = 1024;
        height = 640;
    }

    let debuggerTool = readIni("data", "debTool")
    let loading = new BrowserWindow({
        width: 300,
        height: 300,
        show: false,
        frame: false,
        transparent: true,
        resizable: false,
        maximizable: false
    })
    loading.once('show', () => {
        //禁止拖拽文件到窗口展示
        loading.webContents.on('will-navigate', (event) => event.preventDefault());

        let iconDir = ""
        if (process.env.NODE_ENV === 'production') {
            dbPath = path.dirname(process.execPath) + '/resources/data/' + globalConst.global.db;
            outPath = path.dirname(process.execPath) + '/resources/data/' + globalConst.global.db + '.back';
            iconDir = path.dirname(process.execPath) + '/resources/data/';
        } else {
            dbPath = './data/' + globalConst.global.dbTest;
            outPath = './data/' + globalConst.global.dbTest + '.back';
            iconDir = './data/';
        }
        const sqlLibInstance = SqlLib.getInstance(dbPath)
        const flag = sqlLibInstance.runSql('select * from t_user')
        if (flag === 'sql error') {
            restoreDbFile()
        } else {
            try {
                copyDbFile()
            } catch (err) {
                console.log('拷贝数据库文件失败')
            }
        }
        const scaleFactor = screen.getPrimaryDisplay();
        console.log(scaleFactor)
        mainWindow = new BrowserWindow({
            height: height,
            useContentSize: true,
            width: width,
            frame: false, // 无边框
            // transparent: false,
            fullscreenable: false, // 是否可以进入全屏状态
            webPreferences: {
                webSecurity: false,
                nodeIntegration: true,
                // devTools: debuggerTool && debuggerTool == '1001', //关闭调试工具
                webviewTag: true,
                navigateOnDragDrop: true,
            },
            transparent: true,
            backgroundColor: '#00FFFFFF',
            resizable: false,
            show: false,
            maximizable: false,
            icon: path.join(iconDir, "icons", "bos.ico"),

        });

        setTimeout(() => {
            // long loading page
            mainWindow.loadURL(winURL);

            mainWindow.on('ready-to-show', function () {
                loading.hide()
                loading.close()
                loading.on('closed', () => {
                    loading = null;
                })

                mainWindow.show()
                //注册窗口移动事件
                let windowMove = require('./ipc/window.move')
                windowMove(mainWindow);

                //注册窗口放大缩小关闭事件
                let resizeWindow = require('./ipc/window.resize')
                resizeWindow(mainWindow);
                //主页面渲染完毕后创建空白资源窗口
                creatEmptyResourceWindow(true);

                mainWindow.webContents.on('crashed', () => {
                    const options = {
                        type: 'error',
                        title: '程序异常',
                        message: '美丽科学教学平台出现异常！',
                        buttons: ['重新打开', '退出'],
                    };
                    recordCrash().then(() => {
                        dialog.showMessageBox(options, (index) => {
                            if (index === 0) reloadWindow(mainWindow);
                            else app.quit();
                        });
                    }).catch((e) => {
                        console.log('err', e);
                    });
                })

                //禁止拖拽文件到窗口展示
                mainWindow.webContents.on('will-navigate', (event) => event.preventDefault());
            });

            mainWindow.on('closed', () => {
                mainWindow = null
                //关闭server
                if (server) {
                    server.close();
                }
                let windows = BrowserWindow.getAllWindows();
                windows.forEach(tempWin => {
                    tempWin.close();
                })
            });

            function recordCrash () {
                return new Promise(resolve => {
                    // 崩溃日志请求成功....
                    resolve();
                })
            }

            function reloadWindow (mainWin) {
                if (mainWin.isDestroyed()) {
                    app.relaunch();
                    app.exit(0);
                } else {
                    BrowserWindow.getAllWindows().forEach((w) => {
                        if (w.id !== mainWin.id) w.destroy();
                    });
                    mainWin.reload();
                }
            }
        }, 1500);
    })

    let eduLevel = readIni('data', 'eduLevel');
    let loadUrl = process.env.NODE_ENV === 'development' ?
        path.join(path.resolve('./'), '/static/html/loading.html?eduLevel=' + eduLevel) :
        path.join(global.__static, 'html/loading.html?eduLevel=' + eduLevel);
    loading.loadURL(loadUrl);
    loading.show()

    // 退出上课，更改上课按钮状态
    ipcMain.on('hideSuspensionWindow', (event) => {
        mainWindow.webContents.send("changeStatus");
    })

    // 引入suspension.js，负责悬浮窗口内主进程和渲染进程之间的通信
    require('./suspension');
}

/**
 * 以下代码控制主程序只能被启动一个实例
 * code start
 */
// const shouldQuit = app.makeSingleInstance((commandLine, workingDirectory) => {
//     if (mainWindow) {
//         if (mainWindow.isMinimized()) mainWindow.restore()
//         mainWindow.focus()
//     }
// });
//
// if (shouldQuit) {
//     app.quit()
// };
const shouldQuit = app.requestSingleInstanceLock();
if (!shouldQuit) {
    dialog.showErrorBox("提示", "美丽科学教学平台已运行！");
    app.quit();
}
/**code end*/

// 忽略 https 证书错误
app.commandLine.appendSwitch('--ignore-certificate-errors', 'true');
app.commandLine.appendSwitch('disable-pinch');  // 禁止双指缩放

//转换ini配置文件为utf8格式
let toUtf8 = require('./toutf8');
toUtf8();

//初始化cache路径
let readIni = require('./readini')
let cacheDir = readIni('data', 'dataDir');
if (cacheDir === "self" || cacheDir === "low-update") { //代表是当前目录
    if (process.env.NODE_ENV === 'production') {
        cacheDir = path.dirname(process.execPath) + '/resources/data/';
    } else {
        cacheDir = './data/';
    }
}
app.setPath('userData', path.resolve(cacheDir, "cache"));
app.setPath('appData', path.resolve(cacheDir, "cache"));

//初始化server
let server = require('./ipc/window.server');

app.on('ready', function () {
    createWindow();
    // installExtension(VUEJS_DEVTOOLS)
    //     .then((name) => console.log(`Added Extension:  ${name}`))
    //     .catch((err) => console.log('An error occurred: ', err));
});
// app.whenReady().then(() => {
//     installExtension(VUEJS_DEVTOOLS)
//         .then((name) => console.log(`Added Extension:  ${name}`))
//         .catch((err) => console.log('An error occurred: ', err));
// });
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow()
    }
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
//数据库文件拷贝
function copyDbFile () {
    const fs = require('fs')
    fs.copyFileSync(dbPath, outPath)
}
//数据库文件修复
function restoreDbFile () {
    const fs = require('fs')
    if (fs.existsSync(outPath)) {
        fs.unlinkSync(dbPath)
        fs.renameSync(outPath, dbPath)
        console.log('数据库恢复成功')
        copyDbFile()
    } else {
        console.log('不存在数据库拷贝文件')
    }
}

